define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts'], function ($, undefined, Backend, Table, Form, echarts) {

    var Controller = {
        dashboard: function () {
            // 加载看板数据
            $.ajax({
                url: 'scanwork/bi/dashboard',
                dataType: 'json',
                success: function(ret) {
                    if (ret.code === 1) {
                        $('#orders-count').text(ret.data.orders || 0);
                        $('#plans-count').text(ret.data.plans || 0);
                        
                        if (ret.data.quality && ret.data.quality.length > 0) {
                            var qualityRate = ret.data.quality[0].quality_rate || 0;
                            $('#quality-rate').text(qualityRate + '%');
                        }
                    }
                }
            });
        },
        production_efficiency: function () {
            var table = $("#table");
            Table.api.init({
                extend: {
                    index_url: 'scanwork/bi/production_efficiency' + location.search,
                    table: 'scanwork_production_efficiency',
                }
            });
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'stat_date',
                sortOrder: 'desc',
                columns: [
                    [
                        {field: 'stat_date', title: '日期', formatter: Table.api.formatter.date},
                        {field: 'plan_quantity', title: '计划产量'},
                        {field: 'actual_quantity', title: '实际产量'},
                        {field: 'qualified_quantity', title: '合格产量'},
                        {field: 'output_rate', title: '产出率(%)', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }},
                        {field: 'quality_rate', title: '合格率(%)', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }},
                        {field: 'efficiency_rate', title: '效率(%)', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }}
                    ]
                ]
            });
            Table.api.bindevent(table);
        },
        quality_analysis: function () {
            var table = $("#table");
            Table.api.init({
                extend: {
                    index_url: 'scanwork/bi/quality_analysis' + location.search,
                    table: 'scanwork_quality_statistics',
                }
            });
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'stat_date',
                sortOrder: 'desc',
                columns: [
                    [
                        {field: 'stat_date', title: '日期', formatter: Table.api.formatter.date},
                        {field: 'inspection_quantity', title: '检验数量'},
                        {field: 'qualified_quantity', title: '合格数量'},
                        {field: 'pass_rate', title: '一次合格率(%)', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }},
                        {field: 'defect_rate', title: '不良率(%)', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }}
                    ]
                ]
            });
            Table.api.bindevent(table);
        },
        material_loss: function () {
            var table = $("#table");
            Table.api.init({
                extend: {
                    index_url: 'scanwork/bi/material_loss' + location.search,
                    table: 'scanwork_material_loss',
                }
            });
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'loss_cost',
                sortOrder: 'desc',
                columns: [
                    [
                        {field: 'material_name', title: '物料名称'},
                        {field: 'material_code', title: '物料编码'},
                        {field: 'stat_date', title: '统计日期', formatter: Table.api.formatter.date},
                        {field: 'planned_quantity', title: '计划用量'},
                        {field: 'actual_quantity', title: '实际用量'},
                        {field: 'loss_quantity', title: '损耗数量'},
                        {field: 'loss_rate', title: '损耗率(%)', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }},
                        {field: 'loss_cost', title: '损耗成本', formatter: function(v) { return '¥' + (parseFloat(v) || 0).toFixed(2); }}
                    ]
                ]
            });
            Table.api.bindevent(table);
        },
        employee_performance: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'scanwork/bi/employee_performance' + location.search,
                    add_url: 'scanwork/bi/add',
                    edit_url: 'scanwork/bi/edit',
                    del_url: 'scanwork/bi/del',
                    multi_url: 'scanwork/bi/multi',
                    table: 'scanwork_employee_performance',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'performance_score',
                sortOrder: 'desc',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'employee_name', title: __('员工姓名'), align: 'left'},
                        {field: 'employee_code', title: __('员工编号'), align: 'left'},
                        {field: 'stat_date', title: __('统计日期'), formatter: Table.api.formatter.date, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {field: 'working_hours', title: __('工作时长(小时)'), align: 'center'},
                        {field: 'completed_tasks', title: __('完成任务数'), align: 'center'},
                        {field: 'quality_rate', title: __('质量评分(%)'), align: 'center', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }},
                        {field: 'efficiency_rate', title: __('效率评分(%)'), align: 'center', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2) + '%'; }},
                        {field: 'performance_score', title: __('绩效总分'), align: 'center', formatter: function(v) { return (parseFloat(v) || 0).toFixed(2); }},
                        {field: 'total_wage', title: __('总工资'), align: 'center', formatter: function(v) { return '¥' + (parseFloat(v) || 0).toFixed(2); }},
                        {field: 'operate', title: __('操作'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        costReport: function () {
            // 初始化图表
            var trendChart = echarts.init(document.getElementById('cost-trend-chart'));
            var structureChart = echarts.init(document.getElementById('cost-structure-chart'));

            // 加载数据
            function loadData() {
                $.ajax({
                    url: 'scanwork/bi/costReport',
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        start_date: $('#start_date').val(),
                        end_date: $('#end_date').val()
                    },
                    success: function(res) {
                        if (res.code == 1) {
                            updateSummary(res.data.summary);
                            updateTrendChart(res.data.trend);
                            updateStructureChart(res.data.structure);
                        }
                    }
                });
            }

            // 更新汇总数据
            function updateSummary(data) {
                $('#material-cost').text('¥' + (parseFloat(data.total_material_cost) || 0).toFixed(2));
                $('#labor-cost').text('¥' + (parseFloat(data.total_labor_cost) || 0).toFixed(2));
                $('#overhead-cost').text('¥' + (parseFloat(data.total_overhead_cost) || 0).toFixed(2));
                $('#total-cost').text('¥' + (parseFloat(data.total_cost) || 0).toFixed(2));
                $('#total-revenue').text('¥' + (parseFloat(data.total_revenue) || 0).toFixed(2));
                $('#total-profit').text('¥' + (parseFloat(data.total_profit) || 0).toFixed(2));
                $('#avg-profit-rate').text((parseFloat(data.avg_profit_rate) || 0).toFixed(2) + '%');
            }

            // 更新成本趋势图
            function updateTrendChart(data) {
                var dates = data.map(item => item.date);
                var materialCost = data.map(item => item.material_cost);
                var laborCost = data.map(item => item.labor_cost);
                var overheadCost = data.map(item => item.overhead_cost);
                var totalCost = data.map(item => item.total_cost);

                var option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['物料成本', '人工成本', '制造费用', '总成本']
                    },
                    xAxis: {
                        type: 'category',
                        data: dates
                    },
                    yAxis: {
                        type: 'value',
                        name: '金额(元)'
                    },
                    series: [
                        {
                            name: '物料成本',
                            type: 'line',
                            data: materialCost,
                            smooth: true
                        },
                        {
                            name: '人工成本',
                            type: 'line',
                            data: laborCost,
                            smooth: true
                        },
                        {
                            name: '制造费用',
                            type: 'line',
                            data: overheadCost,
                            smooth: true
                        },
                        {
                            name: '总成本',
                            type: 'line',
                            data: totalCost,
                            smooth: true,
                            lineStyle: {
                                width: 3
                            }
                        }
                    ]
                };
                trendChart.setOption(option);
            }

            // 更新成本结构图
            function updateStructureChart(data) {
                var option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [
                        {
                            name: '成本构成',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            avoidLabelOverlap: false,
                            label: {
                                show: true,
                                formatter: '{b}: {d}%'
                            },
                            data: [
                                {value: data.material_cost || 0, name: '物料成本'},
                                {value: data.labor_cost || 0, name: '人工成本'},
                                {value: data.overhead_cost || 0, name: '制造费用'}
                            ]
                        }
                    ]
                };
                structureChart.setOption(option);
            }

            // 查询按钮
            $('.btn-search').on('click', function() {
                loadData();
            });

            // 初始加载
            loadData();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});

